1   /*
2    * Copyright (C) 2013 The Guava Authors
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5    * in compliance with the License. You may obtain a copy of the License at
6    *
7    * http://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software distributed under the License
10   * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11   * or implied. See the License for the specific language governing permissions and limitations under
12   * the License.
13   */
14  
15  package com.google.common.base;
16  
17  import static com.google.common.base.Preconditions.format;
18  
19  import com.google.common.annotations.Beta;
20  import com.google.common.annotations.GwtCompatible;
21  
22  import javax.annotation.Nullable;
23  
24  /**
25   * Static convenience methods that serve the same purpose as Java language
26   * <a href="http://docs.oracle.com/javase/7/docs/technotes/guides/language/assert.html">
27   * assertions</a>, except that they are always enabled. These methods should be used instead of Java
28   * assertions whenever there is a chance the check may fail "in real life". Example: <pre>   {@code
29   *
30   *   Bill bill = remoteService.getLastUnpaidBill();
31   *
32   *   // In case bug 12345 happens again we'd rather just die
33   *   Verify.verify(bill.status() == Status.UNPAID,
34   *       "Unexpected bill status: %s", bill.status());}</pre>
35   *
36   * <h3>Comparison to alternatives</h3>
37   *
38   * <p><b>Note:</b> In some cases the differences explained below can be subtle. When it's unclear
39   * which approach to use, <b>don't worry</b> too much about it; just pick something that seems
40   * reasonable and it will be fine.
41   *
42   * <ul>
43   * <li>If checking whether the <i>caller</i> has violated your method or constructor's contract
44   *     (such as by passing an invalid argument), use the utilities of the {@link Preconditions}
45   *     class instead.
46   *
47   * <li>If checking an <i>impossible</i> condition (which <i>cannot</i> happen unless your own class
48   *     or its <i>trusted</i> dependencies is badly broken), this is what ordinary Java assertions
49   *     are for. Note that assertions are not enabled by default; they are essentially considered
50   *     "compiled comments."
51   *
52   * <li>An explicit {@code if/throw} (as illustrated below) is always acceptable; we still recommend
53   *     using our {@link VerifyException} exception type. Throwing a plain {@link RuntimeException}
54   *     is frowned upon.
55   *
56   * <li>Use of {@link java.util.Objects#requireNonNull(Object)} is generally discouraged, since
57   *     {@link #verifyNotNull(Object)} and {@link Preconditions#checkNotNull(Object)} perform the
58   *     same function with more clarity.
59   * </ul>
60   *
61   * <h3>Warning about performance</h3>
62   *
63   * <p>Remember that parameter values for message construction must all be computed eagerly, and
64   * autoboxing and varargs array creation may happen as well, even when the verification succeeds and
65   * the message ends up unneeded. Performance-sensitive verification checks should continue to use
66   * usual form: <pre>   {@code
67   *
68   *   Bill bill = remoteService.getLastUnpaidBill();
69   *   if (bill.status() != Status.UNPAID) {
70   *     throw new VerifyException("Unexpected bill status: " + bill.status());
71   *   }}</pre>
72   *
73   * <h3>Only {@code %s} is supported</h3>
74   *
75   * <p>As with {@link Preconditions} error message template strings, only the {@code "%s"} specifier
76   * is supported, not the full range of {@link java.util.Formatter} specifiers. However, note that
77   * if the number of arguments does not match the number of occurrences of {@code "%s"} in the
78   * format string, {@code Verify} will still behave as expected, and will still include all argument
79   * values in the error message; the message will simply not be formatted exactly as intended.
80   *
81   * <h3>More information</h3>
82   *
83   * See
84   * <a href="http://code.google.com/p/guava-libraries/wiki/ConditionalFailuresExplained">Conditional
85   * failures explained</a> in the Guava User Guide for advice on when this class should be used.
86   *
87   * @since 17.0
88   */
89  @Beta
90  @GwtCompatible
91  public final class Verify {
92    /**
93     * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with no
94     * message otherwise.
95     */
96    public static void verify(boolean expression) {
97      if (!expression) {
98        throw new VerifyException();
99      }
100   }
101 
102   /**
103    * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a
104    * custom message otherwise.
105    *
106    * @param expression a boolean expression
107    * @param errorMessageTemplate a template for the exception message should the
108    *     check fail. The message is formed by replacing each {@code %s}
109    *     placeholder in the template with an argument. These are matched by
110    *     position - the first {@code %s} gets {@code errorMessageArgs[0]}, etc.
111    *     Unmatched arguments will be appended to the formatted message in square
112    *     braces. Unmatched placeholders will be left as-is.
113    * @param errorMessageArgs the arguments to be substituted into the message
114    *     template. Arguments are converted to strings using
115    *     {@link String#valueOf(Object)}.
116    * @throws VerifyException if {@code expression} is {@code false}
117    */
118   public static void verify(
119       boolean expression,
120       @Nullable String errorMessageTemplate,
121       @Nullable Object... errorMessageArgs) {
122     if (!expression) {
123       throw new VerifyException(format(errorMessageTemplate, errorMessageArgs));
124     }
125   }
126 
127   /**
128    * Ensures that {@code reference} is non-null, throwing a {@code VerifyException} with a default
129    * message otherwise.
130    *
131    * @return {@code reference}, guaranteed to be non-null, for convenience
132    */
133   public static <T> T verifyNotNull(@Nullable T reference) {
134     return verifyNotNull(reference, "expected a non-null reference");
135   }
136 
137   /**
138    * Ensures that {@code reference} is non-null, throwing a {@code VerifyException} with a custom
139    * message otherwise.
140    *
141    * @param errorMessageTemplate a template for the exception message should the
142    *     check fail. The message is formed by replacing each {@code %s}
143    *     placeholder in the template with an argument. These are matched by
144    *     position - the first {@code %s} gets {@code errorMessageArgs[0]}, etc.
145    *     Unmatched arguments will be appended to the formatted message in square
146    *     braces. Unmatched placeholders will be left as-is.
147    * @param errorMessageArgs the arguments to be substituted into the message
148    *     template. Arguments are converted to strings using
149    *     {@link String#valueOf(Object)}.
150    * @return {@code reference}, guaranteed to be non-null, for convenience
151    */
152   public static <T> T verifyNotNull(
153       @Nullable T reference,
154       @Nullable String errorMessageTemplate,
155       @Nullable Object... errorMessageArgs) {
156     verify(reference != null, errorMessageTemplate, errorMessageArgs);
157     return reference;
158   }
159 
160   // TODO(kevinb): consider <T> T verifySingleton(Iterable<T>) to take over for
161   // Iterables.getOnlyElement()
162 
163   private Verify() {}
164 }